<script setup>
import { ref, watch, onMounted } from 'vue'
import { getEmpList, addEmp } from '@/api/emp'
import { getDeptList } from '@/api/dept'
import { ElMessage,ElMessageBox } from 'element-plus'

// 查询参数对象
const empSearch = ref({
  name: '',
  gender: '',
  begin: '', // 开始入职日期
  end: '',    // 结束入职日期
  date: []
})

// 表格数据
const empList = ref([])

// 分页信息
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 查询按钮点击事件
const search = async () => {
  const queryParam = {
    name: empSearch.value.name,
    gender: empSearch.value.gender,
    begin: empSearch.value.begin,
    end: empSearch.value.end,
    page: pagination.value.currentPage,
    pageSize: pagination.value.pageSize
  }
  const result = await getEmpList(queryParam)
  if (result.code) {
    //渲染数据列表
    empList.value = result.data.rows
    //设置总记录数据
    pagination.value.total = result.data.total
  } else {
    //提示查询失败
    ElMessage.error(result.msg)
  }
}

// 分页事件
const handleSizeChange = (val) => {
  console.log(`每页 ${val} 条`);
  pagination.value.pageSize = val;
  //每页显示条数发生变化时，执行查询
  search()
}
const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`);
  pagination.value.currentPage = val;
  //当前页码发生变化时，执行查询
  search()
}

// 处理职位显示
const getJobDisplay = (jobCode) => {
  const jobMap = {
    1: '班主任',
    2: '讲师',
    3: '学工主管',
    4: '教研主管',
    5: '咨询师'
  };
  return jobMap[jobCode] || '其他';
};

//侦听empSearch中的date值的变化
watch(() => empSearch.value.date, (newValue, oldValue) => {
  if (newValue && newValue.length == 2) {
    empSearch.value.begin = newValue[0]
    empSearch.value.end = newValue[1]
  } else {
    empSearch.value.begin = ''
    empSearch.value.end = ''
  }
})



// 清空按钮点击事件
const resetQuery = () => {
  empSearch.value = {
    name: '',
    gender: '',
    begin: '',
    end: '',
    date: []
  }
  //调用查询
  search()
}


const employeeFormRef = ref(null)
//表单数据模型
const employee = ref({
  username: '',
  name: '',
  gender: '',
  phone: '',
  job: '',
  salary: '',
  deptId: '',
  entryDate: '',
  image: '',
  exprList: []
})

//侦听employee中exprList的变化
watch(() => employee.value.exprList, (newValue, oldValue) => {
  if (newValue && newValue.length > 0) {
    newValue.forEach(item => {
      if (item.date && item.date.length == 2) {
        item.begin = item.date[0]
        item.end = item.date[1]
      } else {
        item.begin = ''
        item.end = ''
      }
    })
  }
}, { deep: true })

//职位列表数据
const jobs = ref([{ name: '班主任', value: 1 }, { name: '讲师', value: 2 }, { name: '学工主管', value: 3 }, { name: '教研主管', value: 4 }, { name: '咨询师', value: 5 }, { name: '其他', value: 6 }])
//性别列表数据
const genders = ref([{ name: '男', value: 1 }, { name: '女', value: 2 }])
//部门列表数据
const deptList = ref([])

// 控制弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('新增员工')

//提供方法，弹窗
const add = () => {
  //控制打开弹窗
  dialogVisible.value = true
  //重置表单数据
  employee.value = {
    username: '',
    name: '',
    gender: '',
    phone: '',
    job: '',
    salary: '',
    deptId: '',
    entryDate: '',
    image: '',
    exprList: []
  }
  //重置表单验证
  if (employeeFormRef.value) {
    employeeFormRef.value.resetFields()
  }
}

//提供方法，添加工作经历
const addExpr = () => {
  employee.value.exprList.push({
    begin: '',
    end: '',
    company: '',
    job: '',
    date: []
  })
}

const deleteExpr = (index) => {
  //从数组中根据索引删除
  employee.value.exprList.splice(index, 1)
}

// 图片上传成功后触发
const handleAvatarSuccess = (response) => {
  employee.value.image = response.data
}
// 文件上传之前触发
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('只支持上传图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('只能上传10M以内图片')
    return false
  }
  return true
}

// 添加员工
const save = async () => {
  //表单验证，验证通过后才可以继续执行
  await employeeFormRef.value.validate()
  const result = await addEmp(employee.value)
  if (result.code) {
    //添加成功
    dialogVisible.value = false
    ElMessage.success("保存成功")
    search()
  } else {
    //添加失败
    ElMessage.error(result.msg)
  }
}

// 表单校验规则
const employeeFormRules = {
  username: [
    { required: true, message: '用户名为必填项', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度应在2-20个字符之间', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '姓名为必填项', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2-10个字符之间', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '性别为必选项', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '手机号为必填项', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' },
    { len: 11, message: '手机号应为11位', trigger: 'blur' }
  ]
}


//查询部门数据
const getDepts = async () => {
  const result = await getDeptList()
  if (result.code) {
    deptList.value = result.data
  } else {
    ElMessage.error(result.msg)
  }
}

//提供钩子函数
onMounted(() => {
  //查询员工数据
  search();
  //查询部门数据
  getDepts()
})
// 添加编辑相关函数
const handleEdit = (index, row) => {
  // 设置弹窗标题为"编辑员工"
  dialogTitle.value = '编辑员工'
  // 控制打开弹窗
  dialogVisible.value = true
  
  // 数据回显 - 将选中的员工数据填充到表单中
  employee.value = {
    id: row.id,
    username: row.username,
    name: row.name,
    gender: row.gender,
    phone: row.phone,
    job: row.job,
    salary: row.salary,
    deptId: row.deptId,
    entryDate: row.entryDate,
    image: row.image,
    exprList: row.exprList ? [...row.exprList] : []
  }
  
  // 处理工作经历中的日期回显
  if (employee.value.exprList && employee.value.exprList.length > 0) {
    employee.value.exprList.forEach(item => {
      if (item.begin && item.end) {
        item.date = [item.begin, item.end]
      }
    })
  }
  // 重置表单验证状态
  if (employeeFormRef.value) {
    employeeFormRef.value.clearValidate()
  }
}
// 添加删除函数
const handleDelete = async (index, row) => {
  // 弹出确认对话框
  ElMessageBox.confirm(
    `确定要删除员工 "${row.name}" 吗？此操作不可恢复。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(async () => {
    // 用户点击确定，执行删除操作
    const result = await deleteEmp(row.id)
    if (result.code) {
      // 删除成功，从列表中删除该行数据
      empList.value.splice(index, 1)
      // 如果当前页只剩一条数据且不是第一页，则返回上一页
      if (empList.value.length === 0 && pagination.value.currentPage > 1) {
        pagination.value.currentPage--
      }
      // 显示删除成功消息
    }
    // 注意：这里需要调用实际的删除API，例如:
    // const result = await deleteEmpById(row.id)
    // 由于你没有提供删除API，这里只是演示逻辑
    
    try {
      // 模拟删除API调用
      // const result = await deleteEmpAPI(row.id)
      
      // 如果API调用成功
      // if (result.code) {
        // 从表格数据中移除该行
        empList.value.splice(index, 1)
        
        // 如果当前页只剩一条数据且不是第一页，则返回上一页
        if (empList.value.length === 0 && pagination.value.currentPage > 1) {
          pagination.value.currentPage--
        }
        
        // 重新查询数据
        search()
        
        // 显示删除成功消息
        ElMessage.success('删除成功')
      // } else {
      //   // 删除失败提示
      //   ElMessage.error(result.msg || '删除失败')
      // }
    } catch (error) {
      // 网络或其他错误
      ElMessage.error('删除请求失败')
    }
  })
  .catch(() => {
    // 用户点击取消或关闭对话框
    ElMessage.info('已取消删除')
  })
}
  

</script>

<template>
  <h3>员工管理</h3>
  <br>
  <div class="emp-search-container">
    <!-- 搜索栏表单 -->
    <el-form :model="empSearch" inline>

      <!-- 姓名输入框 -->
      <el-form-item label="姓名">
        <el-input v-model="empSearch.name" placeholder="请输入员工姓名" clearable style="width: 180px;" />
      </el-form-item>

      <!-- 性别下拉框 -->
      <el-form-item label="性别">
        <el-select v-model="empSearch.gender" placeholder="请选择" clearable style="width: 180px;">
          <el-option label="男" value="1" />
          <el-option label="女" value="2" />
        </el-select>
      </el-form-item>

      <!-- 入职日期范围选择 -->
      <el-form-item label="入职日期">
        <el-date-picker v-model="empSearch.date" type="daterange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" style="width: 260px;" clearable />
      </el-form-item>

      <!-- 查询和清空按钮 -->
      <el-form-item>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button @click="resetQuery">清空</el-button>
      </el-form-item>
    </el-form>

    <!-- 两个按钮 -->
    <el-button type="primary" @click="add">+ 新增员工</el-button>
    <el-button type="danger" @click="">- 批量删除</el-button>

    <br>
    <br>
    <!-- 表格 -->
    <el-table :data="empList" style="width: 100%" border>
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="name" label="姓名" width="120" align="center"></el-table-column>
      <el-table-column prop="gender" label="性别" width="80" align="center">
        <template #default="scope">
          <span>{{ scope.row.gender === 1 ? '男' : '女' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="image" label="头像" width="120" align="center">
        <template #default="scope">
          <el-avatar shape="square" :size="50" :src="scope.row.image" @error="() => true" />
        </template>
      </el-table-column>
      <el-table-column prop="deptName" label="部门名称" width="120" align="center"></el-table-column>
      <el-table-column prop="job" label="职位" width="120">
        <template #default="scope">
          <span>{{ getJobDisplay(scope.row.job) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="entryDate" label="入职日期" width="120" align="center"></el-table-column>
      <el-table-column prop="updateTime" label="最后操作时间" width="230" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <br>
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]" :small="false" :disabled="false" :background="true"
        layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
  </div>
  <!-- 新增、修改员工弹窗 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form ref="employeeFormRef" :model="employee" :rules="employeeFormRules" label-width="80px">
      <!-- 基本信息 -->
      <!-- 第一行 姓名、用户名-->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="employee.username" placeholder="请输入员工用户名，2-20个字"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="employee.name" placeholder="请输入员工姓名，2-10个字"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行 性别、手机号 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="employee.gender" placeholder="请选择性别" style="width: 100%;">
              <el-option v-for="gender in genders" :label="gender.name" :value="gender.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="employee.phone" placeholder="请输入员工手机号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第三行 职位、薪资 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职位">
            <el-select v-model="employee.job" placeholder="请选择职位" style="width: 100%;">
              <el-option v-for="job in jobs" :label="job.name" :value="job.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资">
            <el-input v-model="employee.salary" placeholder="请输入员工薪资"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第四行 所属部门、入职日期 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属部门">
            <el-select v-model="employee.deptId" placeholder="请选择部门" style="width: 100%;">
              <el-option v-for="dept in deptList" :label="dept.name" :value="dept.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期">
            <el-date-picker v-model="employee.entryDate" type="date" style="width: 100%;" placeholder="选择日期"
              format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第五行 图片上传 -->
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="头像">
            <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false"
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="employee.image" :src="employee.image" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 工作经历 -->
      <!-- 第六行 -->
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="工作经历">
            <el-button type="success" size="small" @click="addExpr">+ 添加工作经历</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第七行 ...  工作经历 -->
      <el-row :gutter="3" v-for="(expr, index) in employee.exprList" :key="index">
        <el-col :span="10">
          <el-form-item size="small" label="时间" label-width="80px">
            <el-date-picker v-model="expr.date" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD"></el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item size="small" label="公司" label-width="60px">
            <el-input v-model="expr.company" placeholder="请输入公司名称"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item size="small" label="职位" label-width="60px">
            <el-input v-model="expr.job" placeholder="请输入职位"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="2">
          <el-form-item size="small" label-width="0px">
            <el-button type="danger" @click="deleteExpr(index)">- 删除</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.avatar {
  height: 40px;
}

.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
  /* 添加灰色的虚线边框 */
  border: 1px dashed var(--el-border-color);
}
</style>